<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现购物车结算功能代码</title>
    <link rel="stylesheet" href="../css/style.css" />
</head>

<body>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">

            <a class="fl" id="deleteAll" href="javascript:;">删除选中的商品</a>

            <a class="fl" id="clearAll" href="javascript:;">清理购物车</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    var checkAll = document.getElementsByClassName("check-all")[0]
    var checkOneList = document.getElementsByClassName("check-one");

    var addList = document.getElementsByClassName("add");
    var reduceList = document.getElementsByClassName("reduce");
    var deleteList = document.getElementsByClassName("delete");

    var clearAll = document.getElementById("clearAll");
    var deleteAll = document.getElementById("deleteAll");

    var selectedTotal = document.getElementById("selectedTotal");
    var priceTotal = document.getElementById("priceTotal");

    var tbody = document.querySelector("#cartTable tbody");

    // 页面加载时动态生成购物车
    // console.log("代码开始执行")
    var req = new XMLHttpRequest();  // 0

    req.open("get", "../data/shoppingCar.json", true);  // 1

    req.send();  // 1

    req.onreadystatechange = function () {
        console.log("readyState", req.readyState);  // 2 3 4
        if (req.readyState == 4 && req.status == 200) {
            // console.log(req.responseText);

            var data = JSON.parse(req.responseText);
            console.log(data);

            var html = "";
            data.forEach(({ goodsName, goodsMsg, goodsPrice, goodsImg, buyNum }) => {
                html += ` <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${goodsPrice.toFixed(2)}</td>
                    <td class="count"><span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * buyNum).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>`
            })

            tbody.innerHTML = html;  // 动态生成

            // 生成之后
            // 1.  全选 和  反选  
            // 全选  => 点击全选  所有单选框(check-one)的状态跟随全选(check-all)的状态
            // 反选  => 点击单选  =>  如果所有的单选都选中  => 全选 :选中  否则:不选中
            //                     每次点击都要判断 所有的的单选框是否全部被选中 

            // 全选  => 点击全选  所有单选框(check-one)的状态跟随全选(check-all)的状态
            checkAll.onclick = function () {
                var status = this.checked;
                console.log(status);
                for (var i = 0; i < checkOneList.length; i++) {
                    var checkOne = checkOneList[i];
                    checkOne.checked = status;
                }
                getTotal();
            }

            for (let i = 0; i < checkOneList.length; i++) { // 循环绑定事件
                let checkOne = checkOneList[i];
                checkOne.onclick = function () {
                    // 每次点击 => 都要判断  所有的的单选框是否全部被选中 


                    isAllchecked();
                    getTotal();

                    // 每次点击单选  => 找到选中状态的单选框 
                    // var sum = 0;
                    // var allPrice = 0;
                    // for (var j = 0; j < checkOneList.length; j++) {
                    //     var checkOne = checkOneList[j];
                    //     if (checkOne.checked) {
                    //         var parentTr = parent(parent(checkOne));
                    //         var countInput = parentTr.getElementsByClassName("count-input")[0];
                    //         var subtotalTd = parentTr.getElementsByClassName("subtotal")[0];

                    //         var num = countInput.value * 1;
                    //         var subtotal = subtotalTd.textContent * 1;
                    //         // console.log(num,subtotal);

                    //         sum += num;
                    //         allPrice += subtotal;
                    //     }
                    // }



                }
            }

            // (1)加法要求 
            // 点击 “+”     输入框  数量 加一 
            //             小计更新  =  单价*数量
            //             减号按钮的 “-”  出现
            for (let i = 0; i < addList.length; i++) {
                let add = addList[i];
                add.onclick = function () {
                    console.log(this);

                    // a.   输入框  数量 加一 
                    var countInput = prev(this);
                    console.log(countInput);
                    var num = countInput.value;
                    num++;
                    countInput.value = num;

                    // b.  小计更新  =  单价*数量
                    // 单价: 加号的父元素 =>前一个 =>内容
                    // 数量: num
                    var parentTd = parent(this);
                    var priceTd = prev(parentTd);
                    var subtotalTd = next(parentTd);

                    var price = priceTd.textContent;
                    var subtotal = price * num;

                    subtotalTd.textContent = subtotal.toFixed(2);

                    // c. 减号按钮的 “-”  出现
                    var reduce = prev(countInput);
                    reduce.textContent = "-";

                    getTotal();
                }
            }


            /* 
                 点击减号    输入框  数量 减一   （细节要求  数量为1的时候  不再减）
                       小计更新  =  单价*数量 
                       减之前  判断  如果数量为1  不能减     return false
                       减之后  判断  如果数量为1  减号按钮的 “-” 消失
            
            */
            for (let i = 0; i < reduceList.length; i++) {
                let reduce = reduceList[i];
                reduce.onclick = function () {
                    console.log(this);

                    // a. 输入框  数量 减一   （细节要求  数量为1的时候  不再减）
                    var countInput = next(this);
                    console.log(countInput);
                    var num = countInput.value;
                    // c.  减之前  判断  如果数量为1  不能减
                    if (num == 1) return false;
                    num--;  //自减
                    // d.  减之后  判断  如果数量为1  减号按钮的 “-” 消失
                    if (num == 1) this.textContent = "";

                    countInput.value = num;

                    // b.  小计更新  =  单价*数量
                    // 单价: 加号的父元素 =>前一个 =>内容
                    // 数量: num
                    var parentTd = parent(this);
                    var priceTd = prev(parentTd);
                    var subtotalTd = next(parentTd);

                    var price = priceTd.textContent;
                    var subtotal = price * num;

                    subtotalTd.textContent = subtotal.toFixed(2);

                    getTotal();
                }
            }


            // 两个细节
            // 1.  单删   
            //     每次删除(单删)商品之后  判断  如果剩余的商品全部被选中 => 全选框 变为选中状态

            // 2.  全删 (bug  全删之后  全选框依旧被选中  !!!!)
            //     原因 (isAllChecked  封装时用的是假设法  如果checkOneList为0  flag依旧为true)
            //     解决方法  加一个长度判断   如果checkOneList为0(没有商品)  全选框取消全选


            // 单删   点击每条数据之后的删除   删除该条数据
            for (let i = 0; i < deleteList.length; i++) {
                let del = deleteList[i];
                del.onclick = function () {
                    console.log(this);
                    if (confirm("是否删除该商品?")) {
                        var parentTr = parent(parent(this));
                        parentTr.remove();

                        console.log(checkOneList);

                        // !!!没次删除(单删)商品之后  判断  如果剩余的商品全部被选中 => 全选框 变为选中状态
                        isAllchecked();
                        getTotal();

                    }
                }
            }

            // 多删的问题 
            // var checkOneList = document.getElementsByClassName("check-one");
            // checkOneList  => HTMLCollection (元素的集合  => 会随着页面同类型/类名元素的增加或减少 自动更新集合)

            //     0        1        2         3
            // [checkOne,checkOne,checkOne,checkOne]

            // 清理购物车  删除所有商品
            clearAll.onclick = function () {
                for (var i = 0; i < checkOneList.length; i++) {
                    var checkOne = checkOneList[i];
                    var parentTr = parent(parent(checkOne));
                    parentTr.remove();
                    i--;
                }
                isAllchecked();
                getTotal();
            }

            // 清理购物车  删除所有选中商品
            deleteAll.onclick = function () {
                debugger;
                for (var i = 0; i < checkOneList.length; i++) {
                    var checkOne = checkOneList[i];
                    if (checkOne.checked) {
                        var parentTr = parent(parent(checkOne));
                        parentTr.remove();
                        i--;
                    }
                }

                isAllchecked();
                getTotal();
            }


        }
    }
    console.log("代码开始结束")



    console.log(checkOneList);
    console.log(addList);
    console.log(reduceList);
    console.log(deleteList);

    // ajax动态生成的问题?
    // ajax请求是异步的 => 先执行主线程 => 动态生成元素此时还没有生成 => 获取的集合为[] => 遍历集合绑定事件没有效果

    // 怎么解决?
    // (1)  等待生成之后 再获取元素绑定事件  =>  老赖行为   








    function getTotal() {
        // 找到选中状态的单选框  => 找到数量和小计  => 累加
        var sum = 0;
        var allPrice = 0;
        for (var j = 0; j < checkOneList.length; j++) {
            var checkOne = checkOneList[j];
            if (checkOne.checked) {
                var parentTr = parent(parent(checkOne));
                var countInput = parentTr.getElementsByClassName("count-input")[0];
                var subtotalTd = parentTr.getElementsByClassName("subtotal")[0];

                var num = countInput.value * 1;
                var subtotal = subtotalTd.textContent * 1;
                // console.log(num,subtotal);

                sum += num;
                allPrice += subtotal;
            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }
    function isAllchecked() {
        var flag = true; // 假设都选中 => 如果存在未选中的 推翻假设
        for (var j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j];
            if (!item.checked) {  // item.checked ==false
                flag = false;
                break;
            }
        }
        checkAll.checked = checkOneList.length == 0 ? false : flag;
    }

    function parent(ele) {
        return ele.parentElement || ele.parentNode;
    }
    function prev(ele) {
        return ele.previousElementSibling || ele.previousSibling;
    }
    function next(ele) {
        return ele.nextElementSibling || ele.nextSibling;
    }

</script>

</html>